package com.leoman.work.controller;

import com.leoman.adsindex.dao.AdsIndexDao;
import com.leoman.adsindex.entity.AdsIndex;
import com.leoman.adsindex.service.AdsIndexService;
import com.leoman.banner.entity.Banner;
import com.leoman.banner.service.BannerService;
import com.leoman.barrage.entity.Barrage;
import com.leoman.barrage.service.BarrageService;
import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.comment.service.WorkCommentService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.floatwin.entity.FloatWin;
import com.leoman.floatwin.service.FloatWinService;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserLoginService;
import com.leoman.user.service.UserService;
import com.leoman.utils.HtmlFilter;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import com.leoman.work.entity.*;
import com.leoman.work.service.WorkCreatorService;
import com.leoman.work.service.WorkNovelService;
import com.leoman.work.service.WorkService;
import com.leoman.work.service.WorkSurroundService;
import com.leoman.work.service.impl.WorkServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/15 0015.
 */
@Controller
@RequestMapping(value = "admin/novel")
public class NovelController extends GenericEntityController<Work, Work, WorkServiceImpl> {

    @Autowired
    private WorkService workService;

    @Autowired
    private WorkNovelService workNovelService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkSurroundService workSurroundService;

    @Autowired
    private WorkCreatorService workCreatorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WorkCommentService workCommentService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private AdsIndexService adsIndexService;

    @Autowired
    private FloatWinService floatWinService;


    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "novel/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String name,
                     Long typeList,
                     Integer status,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {
            List<WorkNovel> workNovelList;
            int pageNum = getPageNum(start, length);

            Page<Work> page = workService.page(name, typeList, status, Constant.CATEGORY_TYPE_005, pageNum, length);
            for (Work work : page.getContent()) {
                if (StringUtils.isNotEmpty(work.getCover())) {
                    work.setCover(ImageUtil.clearUploadUrl(work.getCover()));
                }

                // 查询最新小说章节
                workNovelList = workNovelService.findByWorkId(work.getId());
                if (workNovelList.size() != 0) {
                    work.setWorkNovel(workNovelList.get(workNovelList.size() - 1));
                }
            }
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 章节列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexNovel")
    public String indexNovel(Long workId, Model model) {

        List<WorkNovel> workNovelList;
        Work work = workService.queryByPK(workId);

        // 查询最新小说章节
        workNovelList = workNovelService.findByWorkId(work.getId());
        if (workNovelList.size() != 0) {
            work.setWorkNovel(workNovelList.get(workNovelList.size() - 1));
        }
        model.addAttribute("work", work);

        return "novel/novelList";
    }

    /**
     * 查询章节列表
     */
    @RequestMapping(value = "/novelList")
    public void novelList(HttpServletResponse response,
                          Long workId,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<WorkNovel> page = workNovelService.page(workId, pageNum, length);

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 更新下一章
     *
     * @return path
     */
    @RequestMapping(value = "/update")
    public String update(Model model, Long workId, Integer series) {

        Work work = workService.queryByPK(workId);

        model.addAttribute("work", work);
        model.addAttribute("series", series + 1);

        return "novel/update";
    }

    /**
     * 编辑下一章
     *
     * @return path
     */
    @RequestMapping(value = "/updateEdit")
    public String updateEdit(Model model, Long novelId) {

        WorkNovel workNovel = workNovelService.queryByPK(novelId);
        Work work = workNovel.getWork();
        Integer series = workNovel.getSeries();

        workNovel.setDetail(workNovel.getDetail().replaceAll("&lt", "<").replaceAll("&gt", ">"));

        model.addAttribute("workNovel", workNovel);
        model.addAttribute("work", work);
        model.addAttribute("series", series);

        return "novel/update";
    }

    /**
     * 保存更新下一章
     */
    @RequestMapping(value = "/updateSave")
    @ResponseBody
    public Integer updateSave(Long workId,
                              Long workNovelId,
                              String novel,
                              String content,
                              Integer series,
                              Integer status) throws UnsupportedEncodingException {

        /*String msg = request.getParameter("content");

        String str = new String(msg.getBytes("ISO-8859-1"), "UTF-8");*/

        // 过滤敏感字符
        novel = sensitiveWordsService.replaceWord(novel);
        content = sensitiveWordsService.replaceWord(content);

        WorkNovel workNovel;
        if (workNovelId == null) {
            workNovel = new WorkNovel();
            workNovel.setCreateDate(System.currentTimeMillis());
        } else {
            workNovel = workNovelService.queryByPK(workNovelId);
            workNovel.setUpdateDate(System.currentTimeMillis());
        }

        Work work = workService.queryByPK(workId);
        if (status == null) {
            work.setIsEnd(0);
        } else {
            work.setIsEnd(status);
        }
        workService.update(work);

        workNovel.setSeries(series);
        workNovel.setWork(work);
        if (novel.equals("")) {
            workNovel.setName("第" + series + "章");
        } else {
            workNovel.setName(novel);
        }
        List<WorkCreator> tempList = workCreatorService.findWorkId(workNovel.getWork().getId());
        if (null != tempList && tempList.size() > 0) {
            workNovel.setAuthor(tempList.get(0).getUserInfo().getNickname());
        }
        workNovel.setDetail(content);
        workNovel.setUpdateDate(System.currentTimeMillis());

        // 过滤HTML标签，统计富文本字数
        Integer length = HtmlFilter.delHTMLTag(workNovel.getDetail().replaceAll("&lt", "<").replaceAll("&gt", ">")).length();
        workNovel.setLength(length);
        workNovelService.save(workNovel);

        return 1;
    }

    /**
     * 查询主创列表
     */
    @RequestMapping(value = "/creatorList")
    @ResponseBody
    public List<UserInfo> creatorList() {

        return userService.findByStatus();
    }

    /**
     * 查询类型列表
     */
    @RequestMapping(value = "/typeList")
    @ResponseBody
    public List<Category> typeList() {

        return categoryService.findType(Constant.CATEGORY_TYPE_005);
    }


    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    public String add(Model model) {

        List<UserInfo> creatorList = userService.findByStatus();
        model.addAttribute("creatorList", creatorList);

        return "novel/add";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit")
    public String edit(Long workId, Model model) {
        try {
            //Map<String, Object> map = new HashMap<String, Object>();
            //List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            Work work = workService.queryByPK(workId);
            if (StringUtils.isNotEmpty(work.getCover())) {
                work.setCover(ImageUtil.clearUploadUrl(work.getCover()));
            }

            //WorkCreator workCreator = workCreatorService.findByWorkId(workId);

            // 该作品的主创
            List<WorkCreator> workCreatorList = workCreatorService.findWorkId(workId);

            // 周边购买
            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(workId);

            // 所有主创
            List<UserInfo> creatorList = userService.findByStatus();
            model.addAttribute("creatorList", creatorList);

            model.addAttribute("work", work);
            model.addAttribute("workCreatorList", workCreatorList);
            model.addAttribute("workSurroundList", workSurroundList);

            StringBuilder sb = new StringBuilder("");
            for (WorkCreator workCreator : workCreatorList) {
                sb.append(workCreator.getUserInfo().getId() + ",");
            }

            model.addAttribute("tempCreatorIds", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "novel/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long id,
                        String name,
                        Integer seriesCount,
                        Long category,
                        String description,
                        String[] creator,
                        String[] type,
                        String[] welfareList,
                        String[] types,
                        String[] welfareLists,
                        MultipartRequest multipartRequest) throws IOException {

        // 过滤敏感字符
        name = sensitiveWordsService.replaceWord(name);
        description = sensitiveWordsService.replaceWord(description);

        workSurroundService.saveAll(id, name, seriesCount, category, description, creator, type, welfareList,
                types, welfareLists, multipartRequest);

        return 1;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    private Integer delete(Long novelId) {

        return workNovelService.deleteNovel(novelId);
    }

    /**
     * 预览
     */
    @RequestMapping(value = "/detail")
    private String detail(Model model, Long novelId) {

        WorkNovel workNovel = workNovelService.queryByPK(novelId);
        workNovel.setDetail(workNovel.getDetail().replaceAll("&lt", "<").replaceAll("&gt", ">"));

        model.addAttribute("workNovel", workNovel);

        return "novel/detail";
    }

    @RequestMapping(value = "/deleteBatch")
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        List<WorkComment> workCommentList;
        //List<Barrage> barrageList = null;
        for (Long id : arrayId) {

            // 是否链接到广告banner
            List<Banner> bannerList = bannerService.findByTypeAndCategoryId(Constant.POSITION_002, id);
            if (bannerList.size() != 0) {
                return 2;
            }

            // 是否链接到首页推荐
            List<AdsIndex> adsIndexList = adsIndexService.findByTypeAndCategoryId(Constant.POSITION_002, id);
            if (adsIndexList.size() != 0) {
                return 2;
            }

            // 是否链接到浮窗广告
            List<FloatWin> floatWinList = floatWinService.findByTypeAndCategoryId(Constant.POSITION_002, id);
            if (floatWinList.size() != 0) {
                return 2;
            }

            // 删除该视频的周边购买
            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(id);
            for (WorkSurround workSurround : workSurroundList) {
                workSurroundService.delete(workSurround);
            }

            List<WorkNovel> workNovelList = workNovelService.findByWorkId(id);
            for (WorkNovel workNovel : workNovelList) {
                // 查询小说章节评论
                workCommentList = workCommentService.findList(workNovel.getId(), Constant.CATEGORY_TYPE_005, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_YES);
                for (WorkComment workComment : workCommentList) {
                    workCommentService.deleteComment(workComment.getId());
                }
            }

            // 查询小说评论
            workCommentList = workCommentService.findList(id, Constant.CATEGORY_TYPE_005, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_NO);
            for (WorkComment workComment : workCommentList) {
                workCommentService.deleteComment(workComment.getId());
            }
            workService.deleteWork(id);
        }
        return 1;
    }

    @RequestMapping(value = "/deleteBatchNovel")
    @ResponseBody
    public Integer deleteBatchNovel(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            workNovelService.deleteNovel(id);
        }
        return 1;
    }

}
